package com.xhapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.xhapi.config.XfXhConfig;
import com.xhapi.mapper.HistoryQuestionByAiMapper;
import com.xhapi.messageQueue.producer.Producer;
import com.xhapi.pojo.dto.QADTO;
import com.xhapi.pojo.entity.HistoryQuestionByAi;
import com.xhapi.pojo.vo.HistoryQuestionByAiVO;
import com.xhapi.pojo.vo.QaVO;
import com.xhapi.service.AskService;
import com.xhapi.service.IHistoryQuestionByAiService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhapi.utils.knowledgeBaseUtils.ChatDocUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * AI自动生成历史记录题库 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HistoryQuestionByAiServiceImpl extends ServiceImpl<HistoryQuestionByAiMapper, HistoryQuestionByAi> implements IHistoryQuestionByAiService {
    private final ChatDocUtil chatDocUtil;
    private final XfXhConfig xfXhConfig;
    private final AskService askService;
    private final Producer producer;
    private static final String chatUrl = "wss://chatdoc.xfyun.cn/openapi/chat";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Override
    @Transactional
    public List<HistoryQuestionByAiVO> createQA(QADTO qadto) {
        // 向知识库提问获取问题，解析，答案
        String subject = qadto.getSubject();
        String[] fileIds = {
                "b0270baa0f3e4756a43c78193447f688",
                "e67757cd55de4305bcefa0dd04dfe256",
                "03238950185044fea9e86baa5902465a",
                "ebad6883dd8c4cc69b96d18e85cae79b",
                "aa0226565be24c408353a84eccf32ba5"
        };
        String question = "请出" + qadto.getCount() + "道" + qadto.getSubject() + "科目的简答题目要求难度为" + qadto.getDifficulty() +
                "要求你的输出格式为{\"question\":\"你出的问题\",\"answer\":\"问题的正确答案\",\"analysis\":\"这道问题的解析\"," +
                "\"score\":你为这道题设定的分值，不要超过10分}";
        //log.info(question);
        String chat = chatDocUtil.chat(chatUrl, fileIds, question, xfXhConfig.getAppId(), xfXhConfig.getApiSecret());
        // 6.2 讯飞改了生成格式，这里chat多了一对{}，需要剔除

        log.info("以下为回答结果");
        log.info(chat);
        // 接下来解析chat中的结果，把数据存放至数据库中，并返回问题给前端
        List<HistoryQuestionByAi> list = new ArrayList<>();
        // 通过gson库解析json数据
        Gson gson = new Gson();
        // 解析字符串使用正则表达式通过 {} 进行切割
        String regex = "\\{[^}]*\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(chat);

        while (matcher.find()) {
            HistoryQuestionByAi questionByAi = gson.fromJson(matcher.group(), HistoryQuestionByAi.class);
            questionByAi.setUpdateTime(LocalDateTime.now().toString());
            questionByAi.setSubject(qadto.getSubject());
            // TODO 这里需替换成真实Id
            questionByAi.setUserId(20224001);
            list.add(questionByAi);
        }
        // 减少数据库IO，这里直接把数据批推进数据库
        saveBatch(list);

        // 这里通过rabbitMQ实现异步双写，把内容写入ES
        producer.send("writeInEsExchange","writeInEsKey",list);
        // 最后返回的是把答案去掉的实体类

        return BeanUtil.copyToList(list, HistoryQuestionByAiVO.class);
    }

    @Override
    public QaVO analyzeQA(Integer id, String myAnswer) throws IOException {
        HistoryQuestionByAi questionByAi = getById(id);
        String question = questionByAi.getQuestion();
        String answer = questionByAi.getAnswer();
        String analysis = questionByAi.getAnalysis();
//        log.info("正确答案："+answer);
//        log.info("我的答案："+myAnswer);
        MediaType mediaType = MediaType.parse("application/json");
        String content = """
                {
                    "text_1":"%s",
                    "text_2":"%s"
                }
                """.formatted(answer, myAnswer);
        RequestBody body = RequestBody.create(mediaType, content);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet?charset=UTF-8&access_token=24.c65cffb2f7e644979992d6cbccb72700.2592000.1721549751.282335-70588427")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        JSONObject jsonObject = new JSONObject(string);
        // 获取score的值
        double score = jsonObject.getDouble("score");
        score= Double.parseDouble(String.format("%.2f",score));
        log.info("相似度：" + score);
        return QaVO.builder()
                .question(question)
                .answer(answer)
                .analysis(analysis)
                .score(score * questionByAi.getScore())
                .build();
    }
}
